package com.example.ashmemclient

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.os.Parcel
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    lateinit var conn: ServiceConnection
    lateinit var serviceIntent: Intent
    var bind = false;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        serviceIntent = Intent("com.example.ashmemservice.RemoteService")
        serviceIntent.setPackage("com.example.ashmemservice")
        conn = object : ServiceConnection {
            override fun onServiceDisconnected(name: ComponentName?) {
                Log.e("kobe-result", "onServiceDisconnected")
                tv.text = "onServiceDisconnected"
            }

            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                var data = Parcel.obtain()
                var reply = Parcel.obtain()
                if (service == null) {
                    Log.e("kobe-result", "service null");
                    tv.text = "binder null"
                    return
                }
                try {
                    //通过binder机制跨进程调用服务端的接口
                    service.transact(1, data, reply, 0)
                    //获得RemoteService创建的匿名共享内存的fd
                    var fd = reply.readFileDescriptor().getFileDescriptor()
                    //读取匿名共享内存中的数据，并打印log
//                    var br = BufferedReader(FileReader(fd))
//                    var str = br.readLine()
//                    Log.v("kobe-result", str)
//                    tv.text = str

                    var bm = BitmapFactory.decodeFileDescriptor(fd)
                    iv.setImageBitmap(bm)
                } catch (e: Exception) {
                    e.printStackTrace();
                }
            }
        }
        tv.setOnClickListener {
            bindAndFetchData()
        }
    }

    private fun bindAndFetchData() {
        //绑定服务
        bind = bindService(serviceIntent, conn, Context.BIND_AUTO_CREATE)
        if (!bind) {
            Log.e("kobe-result", "bind service failed")
            tv.text = "bind service failed"
        }
    }

    override fun onDestroy() {
        if (bind) {
            unbindService(conn)
        }
        super.onDestroy()
    }
}
